package com.yueke.yuekeshop.shopweb.service.impl;


import com.alibaba.fastjson.JSON;
import com.yueke.common.core.domain.shop.YuekeShopGoods;
import com.yueke.common.core.domain.shop.YuekeShopOrderItem;
import com.yueke.common.core.domain.shop.YuekeShopOrders;
import com.yueke.common.core.domain.shop.YuekeShopOrdersOrOrdersItem;
import com.yueke.common.core.exception.WoniuException;
import com.yueke.yuekeshop.shopmodel.dto.orders.GoodOrdersDetails;
import com.yueke.yuekeshop.shopmodel.dto.orders.UserGoodOrdersDto;
import com.yueke.yuekeshop.shopmodel.params.car.GoodsCarParams;
import com.yueke.yuekeshop.shopmodel.params.orders.AlibabaPayParams;
import com.yueke.yuekeshop.shopmodel.params.orders.OrdersListParams;
import com.yueke.yuekeshop.shopmodel.params.orders.UserOrdersStatus;
import com.yueke.yuekeshop.shopweb.mapper.ShopGoodsMapper;
import com.yueke.yuekeshop.shopweb.mapper.ShopOrderItemMapper;
import com.yueke.yuekeshop.shopweb.mapper.ShopOrdersMapper;
import com.yueke.yuekeshop.shopweb.mapper.ShopOrdersOrOrderItemMapper;
import com.yueke.yuekeshop.shopweb.service.ShopCarService;
import com.yueke.yuekeshop.shopweb.service.ShopOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class ShopOrdersServiceImpl implements ShopOrdersService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Autowired
    private ShopOrderItemMapper shopOrderItemMapper;

    @Autowired
    private ShopOrdersMapper shopOrdersMapper;

    @Autowired
    private ShopOrdersOrOrderItemMapper ordersOrOrderItemMapper;

    @Autowired
    private ShopCarService shopCarService;

    /**
     * 抽取出订单编号  C:营地ID+T:时间戳
     * @param userId
     * @return
     */
    public String getOrdersNumber(Integer userId,long startTime) {
        return "U"+userId+"T"+startTime;
    }

    /**
     * 抽取需要营地上架商品ids集合
     * @param campsiteList
     * @return
     */
    private List<String> getGoodsOnIds(Set<String> campsiteList) {
        List<String>  goodsOnIds = new ArrayList<>();
        campsiteList.forEach(campsiteId ->{
            Set<String> goodsIds = stringRedisTemplate.opsForZSet().range("campsite:" + campsiteId+ ":goods:on:ids", 0, -1);
            goodsOnIds.addAll(goodsIds);
            Collections.reverse(goodsOnIds); /* 控制输出顺序的地方 */
        });
        return goodsOnIds;
    }

    /**
     * 新增订单
     * @param goodsIds
     * @return
     */
    @Override
    public UserGoodOrdersDto addGoodsOrder(List<String> goodsIds) {
        int userId = 1;
        Set<String> campsiteList = stringRedisTemplate.opsForZSet().range("campsite:ids", 0, -1);
        List<String> goodsOnIds = this.getGoodsOnIds(campsiteList);
        System.out.println(goodsOnIds);
        boolean isContainsOn = goodsOnIds.containsAll(goodsOnIds);
        if (!isContainsOn){
            throw new WoniuException(404,"商品或已失效");
        }
        YuekeShopOrders yuekeShopOrders = new YuekeShopOrders();
        BigDecimal sumPrice = new BigDecimal(0.0);
        yuekeShopOrders.setUserId(userId);
        long startTime = System.currentTimeMillis();
        String ordersNumber = this.getOrdersNumber(userId, startTime);
        yuekeShopOrders.setOrdersNum(ordersNumber);
        yuekeShopOrders.setOrdersStartTime(startTime);

        List<Integer> orderItemIds = new ArrayList<>();
        goodsIds.stream().forEach(goodsId ->{
            Map<Object, Object> goodsOrdersMap = stringRedisTemplate.opsForHash().entries("userId:" + userId + ":id:" + goodsId);
            GoodsCarParams goodsCarParams = JSON.parseObject(JSON.toJSONString(goodsOrdersMap), GoodsCarParams.class);
            Integer goodsOrdersCount = goodsCarParams.getGoodsOrdersCount();
            YuekeShopGoods yuekeShopGoods = shopGoodsMapper.selectById(goodsId);
            int count = yuekeShopGoods.getGoodsInventory() - goodsOrdersCount;
            yuekeShopGoods.setGoodsInventory(count);
            int i = shopGoodsMapper.updateById(yuekeShopGoods);
            YuekeShopOrderItem yuekeShopOrderItem = new YuekeShopOrderItem();
            BeanUtils.copyProperties(yuekeShopGoods,yuekeShopOrderItem);
            yuekeShopOrderItem.setOrderItemCount(goodsOrdersCount);
            yuekeShopOrderItem.setOrderItemPrice(yuekeShopGoods.getGoodsPrice());
            BigDecimal sumItemPrice =yuekeShopGoods.getGoodsPrice().multiply(BigDecimal.valueOf(goodsOrdersCount));
            yuekeShopOrderItem.setOrderItemSumPrice(sumItemPrice);
            int insert = shopOrderItemMapper.insert(yuekeShopOrderItem);
            sumPrice.add(sumItemPrice);
            orderItemIds.add(yuekeShopOrderItem.getOrderItemId());
            shopCarService.deleteOrdersCar(Integer.parseInt(goodsId+""));
        });
        yuekeShopOrders.setOrdersSumPrice(sumPrice);
        yuekeShopOrders.setOrdersStatus("待付款");
        int insert = shopOrdersMapper.insert(yuekeShopOrders);
        orderItemIds.stream().forEach(orderItemId ->{
            YuekeShopOrdersOrOrdersItem yuekeShopOrdersOrOrdersItem = new YuekeShopOrdersOrOrdersItem();
            yuekeShopOrdersOrOrdersItem.setOrdersId(yuekeShopOrders.getOrdersId());
            yuekeShopOrdersOrOrdersItem.setOrderItemId(orderItemId);
            ordersOrOrderItemMapper.insert(yuekeShopOrdersOrOrdersItem);
        });
        UserGoodOrdersDto userGoodOrdersDto = new UserGoodOrdersDto();
        BeanUtils.copyProperties(yuekeShopOrders,userGoodOrdersDto);
        return userGoodOrdersDto;
    }

    /**
     * 关闭订单
     * @param ordersId
     */
    @Override
    public void updateGoodsOrderStatus(Integer ordersId) {
        YuekeShopOrders yuekeShopOrders = shopOrdersMapper.selectById(ordersId);
        YuekeShopOrders newYuekeShopOrders = yuekeShopOrders.setOrdersStatus("关闭订单");
        shopOrdersMapper.updateById(newYuekeShopOrders);
    }

    /**
     * 支付功能
     * @param alibabaPayParams
     */
    @Override
    public void alibabaPayOrder(AlibabaPayParams alibabaPayParams) {

    }

    /**
     * 查询订单列表(可模糊)
     * @param ordersListParams
     * @return
     */
    @Override
    public List<UserGoodOrdersDto> selectOrdersList(OrdersListParams ordersListParams) {

        return null;
    }

    /**
     * 查询商品订单详情
     * @param ordersId
     * @return
     */
    @Override
    public GoodOrdersDetails selectOrdersById(Integer ordersId) {
        return null;
    }

    /**
     * 用户查询个人订单
     * @param userOrdersStatus
     * @return
     */
    @Override
    public List<GoodOrdersDetails> selectUserOrdersId(UserOrdersStatus userOrdersStatus) {
        return null;
    }


}
